package cn.edu.abtu.config.security.service;

import cn.edu.abtu.entity.SysPermission;
import cn.edu.abtu.entity.SysUser;
import cn.edu.abtu.service.SysPermissionService;
import cn.edu.abtu.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/*
* 用户认证处理器类
* */
@Component
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        SysUser sysUser = sysUserService.getUserByUsername(username);
        // 判断对象是否为空,如果对象为空,则表示登录失败
        if (Objects.isNull(sysUser)){
            throw new UsernameNotFoundException("用户名或密码错误! ");
        }
        // 根据用户id查询用户所拥有的权限列表
        List<SysPermission> permissionList = sysPermissionService.getPermissionListByUserId(sysUser.getId());
        List<String> collect = permissionList.stream()
                .filter(Objects::nonNull)
                .map(SysPermission::getCode).filter(Objects::nonNull)
                .collect(Collectors.toList());
        // 装换成数组
        String[] strings = collect.toArray(new String[collect.size()]);
        //设置权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        //设置菜单列表
        sysUser.setAuthorities(authorityList);
        sysUser.setPermissionList(permissionList);
        // 查询成功 !
        return sysUser;
    }
}
